<?php 

//require_once APPLICATION_PATH . '/../library/Doctrine/Common/ClassLoader.php';


use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration as DoctrineConfiguration,
Doctrine\Common\EventManager as DoctrineEventManager,
Doctrine\ORM\EntityManager as DoctrineEntityManager,
Doctrine\Common\Cache\ApcCache as DoctrineApcCache,
Doctrine\Common\Cache\ArrayCache as DoctrineArrayCache;

class Default_Bootstrap extends Zend_Application_Module_Bootstrap
{
	/**
	 * Constructor
	 *
	 * @param  Zend_Application|Zend_Application_Bootstrap_Bootstrapper 
	 *     $application
	 * @return void
	 */
	public function __construct($application)
	{
		parent::__construct($application);
		$this->_loadModuleConfig();
	}
 
	
	/**
	 *
	 * load a module specific config file
	 */
	protected function _loadModuleConfig()
	{
		// would probably better to use
		$configFile = APPLICATION_PATH
		. '/modules/'
		. '/default/'
		. '/configs/module.ini';
	
		if (!file_exists($configFile)) {
			return;
		}
	
		$config = new Zend_Config_Ini($configFile, $this->getEnvironment());
		$this->setOptions($config->toArray());
		
		# get registery
		$this->_registry = Zend_Registry::getInstance();
		
		# save new database adapter to registry
		$this->_registry->config = new stdClass();
		$this->_registry->config->module = $config;
			
		//var_dump($config);
	}	
	
	
		
	protected function _initAutoload()
	{	    
		$autoloader = Zend_Loader_Autoloader::getInstance();
		$resourceloader= new Zend_Loader_Autoloader_Resource(array(
		'basePath'=>APPLICATION_PATH.'/modules/default',
		'namespace'=>'Default',
		'resourceTypes'=> array('form'=>array('path'=>'forms/','namespace'=>'Form'),
		'model'=>array('path'=>'models/','namespace'=>'Model'))
		));
		$autoloader->pushAutoloader($resourceloader);
	}
	
	protected function _initView()
	{		 
		$view = new Zend_View();
	
		//DOCTYPE
		$view->doctype('HTML5');
	
		//TITLE
		$view->headTitle('Hoi An Express');
		$view->headTitle()->setSeparator(' - ');
	
		//METATAGS
		$view->headMeta()->appendName('keywords', 'travel agency, vietnam');
		$view->headMeta()->appendName('description', 'Hoi An Express is the best travel agency in Vietnam');
		$view->headMeta()->appendName('robots', 'allow');
		$view->headMeta()->appendName('copyright', 'Starseed 2012');
	
		//HEADLINK
		$view->headLink()->appendStylesheet('/css/default/main.css');
	
		//-JQuery
		$view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');
		$view->jQuery()->enable();
		$view->jQuery()->uiEnable();
		$view->jQuery()->setLocalPath('/js/library/jquery/js/jquery-1.6.4.js')
		->setUILocalPath('/js/library/jquery/js/jquery-ui-1.8.17.custom.min.js')
		->addJavascriptFile('/js/default/base.js')
		->addJavascriptFile('/js/default/rotate3di.js')
		->addJavascriptFile('/js/default/swfobject/swfobject.js')
		->addJavascriptFile('/js/default/main.js');
		// OTHER JS
		$view->headScript()->appendFile('/js/library/jquery/js/jquery.alerts.js');
		$view->headScript()->appendFile('/js/library/modernizr.js');
		$view->headScript()->appendFile('/js/library/tab.js');
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
		$viewRenderer->setView($view);
		Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
		
		/**
		 * Setup the Custom Helpers
		 */
		Zend_Controller_Action_HelperBroker::addPrefix('HAE_Helper');
		 
	}
		
	protected function _initTranslate()
	{
		$session = new Zend_Session_Namespace();
		$lang='';
		if($session->__isset("lang"))
		{
			$lang=$session->lang;
		}else {
			$lang='en';
		}
		
		$translate = new Zend_Translate(
        array(
        'adapter' => 'tmx',
        'content' => APPLICATION_PATH.'/configs/language.tmx',
        'locale'  => $lang
    	));
    	$registry= Zend_Registry::getInstance();
    	$registry->set('Zend_Translate', $translate);
    	$registry->set('lang', $lang);
	}
	
	protected function _initNavigation()
	{		
		$config = new Zend_Config_Xml(APPLICATION_PATH . '/modules/default/configs/navigation.xml', 'nav');
		$navigation = new Zend_Navigation($config);
		
		$registry= Zend_Registry::getInstance();
		$registry->set("navigation", $navigation);	
	}
	
// 	protected function _initFrontController(){
	   
// 		$front = Zend_Controller_Front::getInstance();
// 		$front->addControllerDirectory(APPLICATION_PATH . "/modules/default/controllers");
		 
// 		$config = new Zend_Config_Ini(APPLICATION_PATH . '/modules/default/configs/routers.ini', 'thietlap');
// 		$router = new Zend_Controller_Router_Rewrite();
	
// 		$router = $router->addConfig($config, 'routes');
	
// 		$front->setRouter($router);
	
// 		return $front;
// 	}
	protected function  _initRewriteUrl()
	{
		$ctrl = Zend_Controller_Front::getInstance();
		$router = $ctrl->getRouter(); // returns a rewrite router by default
		
		$route = new Zend_Controller_Router_Route_Regex('tour/(.+)',array('module'  => 'default','controller' => 'tour','action'     => 'index'),array(1 => 'country'),'tour/%s');
		$router->addRoute('tour', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('tour/(.+)/(.+)',array('module'  => 'default','controller' => 'tour','action'     => 'listtour'),array(1 => 'country',2 => 'tourtype'),'tour/%s/%s');
		$router->addRoute('tourlist', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('shorttour/(.+)/(.+)-(.+)',array('module'  => 'default','controller' => 'tour','action'=> 'detailsorttour'),array(1 => 'country',2 => 'tourId',3 => 'nametour'),'shorttour/%s/%s-%s');
		$router->addRoute('detailshorttour', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('packagetour/(.+)/(.+)-(.+)',array('module'  => 'default','controller' => 'tour','action'=> 'detailpackagetour'),array(1 => 'country',2 => 'tourId',3 => 'nametour'),'packagetour/%s/%s-%s');
		$router->addRoute('detailpackagetour', $route);
				
		$route = new Zend_Controller_Router_Route_Regex('honeymoon',array('module'  => 'default','controller' => 'honeymoon','action'     => 'index'),array(),'honeymoon');
		$router->addRoute('honeymoon', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('mice',array('module'  => 'default','controller' => 'mice','action'     => 'index'),array(),'mice');
		$router->addRoute('mice', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('travelservice',array('module'  => 'default','controller' => 'travelservice','action'     => 'index'),array(),'honeymoon');
		$router->addRoute('travelservice', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('maketrip',array('module'  => 'default','controller' => 'maketrip','action'     => 'index'),array(),'maketrip');
		$router->addRoute('maketrip', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('pro',array('module'  => 'default','controller' => 'pro','action'     => 'index'),array(),'pro');
		$router->addRoute('pro', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('admin',array('module'  => 'admin','controller' => 'index','action'     => 'index'),array(),'admin');
		$router->addRoute('admin', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('about',array('module'  => 'default','controller' => 'about','action'     => 'index'),array(),'about');
		$router->addRoute('about', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('promotion',array('module'  => 'default','controller' => 'promotion','action'     => 'index'),array(),'promotion');
		$router->addRoute('promotion', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('testimonial',array('module'  => 'default','controller' => 'testimonial','action'     => 'index'),array(),'testimonial');
		$router->addRoute('testimonial', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('privilege',array('module'  => 'default','controller' => 'privilege','action'     => 'index'),array(),'privilege');
		$router->addRoute('privilege', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('newsletter',array('module'  => 'default','controller' => 'newsletter','action'     => 'index'),array(),'newsletter');
		$router->addRoute('newsletter', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('gallery',array('module'  => 'default','controller' => 'gallery','action'     => 'index'),array(),'gallery');
		$router->addRoute('gallery', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('insurance',array('module'  => 'default','controller' => 'insurance','action'     => 'index'),array(),'insurance');
		$router->addRoute('insurance', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('contact',array('module'  => 'default','controller' => 'contact','action'     => 'index'),array(),'contact');
		$router->addRoute('contact', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('about/partner',array('module'  => 'default','controller' => 'about','action'     => 'partner'),array(),'about/partner');
		$router->addRoute('partner', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('about/career',array('module'  => 'default','controller' => 'about','action'     => 'career'),array(),'about/career');
		$router->addRoute('career', $route);
		
// 		$route = new Zend_Controller_Router_Route_Regex('([^\.]+)\.html',array('module'  => 'default','controller' => 'about','action' => 'detailcareer'),array(1 => 'id'),	'%d.html');
// 		$router->addRoute('detailcareer', $route);
		$route = new Zend_Controller_Router_Route_Regex('about/jobs/(\d+)-(.+)\.html',array('module'  => 'default','controller' => 'about','action' => 'detailcareer'),array(1 => 'id', 2 => 'alias'), 'about/jobs/%d-%s.html');
		$router->addRoute('detailcareer', $route);
		
		
		$route = new Zend_Controller_Router_Route_Regex('about/terms',array('module'  => 'default','controller' => 'fag','action'     => 'terms'),array(),'faq/terms');
		$router->addRoute('terms', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('about/privacy',array('module'  => 'default','controller' => 'fag','action'     => 'terms'),array(),'faq/privacy');
		$router->addRoute('privacy', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('sitemap',array('module'  => 'default','controller' => 'sitemap','action'     => 'index'),array(),'sitemap');
		$router->addRoute('sitemap', $route);
		
		$route = new Zend_Controller_Router_Route_Regex('contact',array('module'  => 'default','controller' => 'contact','action'     => 'index'),array(),'contact');
		$router->addRoute('contact', $route);
	}
	
// 	public function _initRequest()
// 	{
// 		$this->bootstrap('frontController');
//     	$countryname = $this->getResource('frontController')->getRequest()->getParam('country');
//     	$countryId=1;
//     	switch ($countryname) {
//     		case 'muti':
//     		    $countryId=0;
//     		    break;
//     		case 'vietnam':
//     		    $countryId=1;
//     		    break;
//     		case 'laos':
//     		   	$countryId=2;
//     		    break;
//     		case 'cambodia':
//     		    $countryId=3;
//     		    break;
//     		case 'myanmar':
//     		    $countryId=4;
//     		    break;
//     		case 'thailand':
//     		    $countryId=5;
//     		    break;
//     	}
//     	$registry= Zend_Registry::getInstance();
// 		$registry->set("countryId", $countryId);
		
// 	}
	
	
 	protected function _initZFDebug()
	 {
		$autoloader = Zend_Loader_Autoloader::getInstance();
		$autoloader->registerNamespace('ZFDebug');
		
		$options = array(
			'plugins' => array('Variables', 
							   'File' => array('base_path' => '/'),
							   'Memory', 
							   'Time', 
							   'Registry', 
							   'Exception')
		);
		
		# Instantiate the database adapter and setup the plugin.
		# Alternatively just add the plugin like above and rely on the autodiscovery feature.
		if ($this->hasPluginResource('db')) {
			$this->bootstrap('db');
			$db = $this->getPluginResource('db')->getDbAdapter();
			$options['plugins']['Database']['adapter'] = $db;
		}
	
		# Setup the cache plugin
		if ($this->hasPluginResource('cache')) {
			$this->bootstrap('cache');
			$cache = $this->getPluginResource('cache')->getDbAdapter();
			$options['plugins']['Cache']['backend'] = $cache->getBackend();
		}
	
// 		$debug = new ZFDebug_Controller_Plugin_Debug($options);
// 		$this->bootstrap('frontController');
// 		$frontController = $this->getResource('frontController');
// 		$frontController->registerPlugin($debug);
	}	
	
	/**
	 * Initializes and returns Doctrine ORM entity manager
	 *
	 * @return \Doctrine\ORM\EntityManager
	 * 
	 */
	
	public function _initClassLoaders()
	{
		//Doctrine loader
		require_once (APPLICATION_PATH .
				DIRECTORY_SEPARATOR . '..' .
				DIRECTORY_SEPARATOR . 'library' .
				DIRECTORY_SEPARATOR . 'Doctrine' .
				DIRECTORY_SEPARATOR . 'Common' .
				DIRECTORY_SEPARATOR . 'ClassLoader.php'
		);
		
		$doctrineAutoloader = new \Doctrine\Common\ClassLoader('Doctrine', APPLICATION_PATH .
				DIRECTORY_SEPARATOR . '..' .
				DIRECTORY_SEPARATOR . 'library'
		);
		$doctrineAutoloader->register();
		
		//Add an autonamespace for the entities
		$serviceAutoloader = new \Doctrine\Common\ClassLoader('Entities', APPLICATION_PATH .
				DIRECTORY_SEPARATOR . '..' .
				DIRECTORY_SEPARATOR . 'doctrine'
		);
		$serviceAutoloader->register();
				
		//Add an autonamespace for the repositories
		$serviceAutoloader = new \Doctrine\Common\ClassLoader('Repositories', APPLICATION_PATH .
				DIRECTORY_SEPARATOR . '..' .
				DIRECTORY_SEPARATOR . 'doctrine'
		);
		$serviceAutoloader->register();
		
		//Add an autonamespace for the services
		$serviceAutoloader = new \Doctrine\Common\ClassLoader('Services', APPLICATION_PATH .
				DIRECTORY_SEPARATOR . '..' .
				DIRECTORY_SEPARATOR . 'doctrine'
		);
		$serviceAutoloader->register();
		
		//Doctrine Extensions library 
		$classLoader = new \Doctrine\Common\ClassLoader('DoctrineExtensions', APPLICATION_PATH .
				DIRECTORY_SEPARATOR . '..' .
				DIRECTORY_SEPARATOR . 'library'
		);
		$classLoader->register();
				
		$autoloader = Zend_Loader_Autoloader::getInstance();		
		$autoloader->pushAutoloader(array($serviceAutoloader, 'loadClass'), 'Entities');
		$autoloader->pushAutoloader(array($serviceAutoloader, 'loadClass'), 'Repositories');
		
		
		
	}
	
	/**
	 * Initializes and returns Doctrine ORM entity manager
	 *
	 * @return \Doctrine\ORM\EntityManager
	 * @todo Resource configurator like http://framework.zend.com/wiki/x/0IAbAQ
	 */	
	
	protected function _initDoctrine()
	{        
		
		$this->bootstrap(array('classLoaders', 'doctrineCache'));
		
		// Parameters in .ini files		
		$zendConfig = $this->getOptions();
				
		// Database : driver, host, user, password and dbname
		$connectionParameters = $zendConfig['doctrine']['connection'];
				
		// Configuration : now initialize the configuration object
		$configuration = new DoctrineConfiguration();
		
		// Metatada tags : used to avoid parsing all mapping information every time the framework is initialized.
		$configuration->setMetadataCacheImpl($this->getResource('doctrineCache'));

		// For performance reasons, it is also recommended to use a result cache
		$configuration->setResultCacheImpl($this->getResource('doctrineCache'));
				
		// If true, Doctrine 2 will generate proxy classes for your entities on the fly. Reduce performance and should be disabled in the production
		$configuration->setAutoGenerateProxyClasses($zendConfig['doctrine']['autoGenerateProxyClasses']);
				
		// The directory, where your proxy classes live
		$configuration->setProxyDir($zendConfig['doctrine']['proxyPath']);
		
		// The proxy classes' namespace
		$configuration->setProxyNamespace($zendConfig['doctrine']['proxyNamespace']);
				
		// Language description we want to use for the mapping information
		$configuration->setMetadataDriverImpl(
				$configuration->newDefaultAnnotationDriver(
						$zendConfig['doctrine']['entityPath']));
					
		// Manager : create an event manager
		$eventManager = new DoctrineEventManager();
				
		// now we have everything required to initialize the entity manager
		$entityManager = DoctrineEntityManager::create($connectionParameters, $configuration, $eventManager);
				
		Zend_Registry::set('doctrine', $entityManager);
				
		//$this->_registry->doctrine      = new stdClass();
		//$this->_registry->doctrine->_em = DoctrineEntityManager::create($connectionParameters, $configuration, $eventManager);

		return $entityManager;
	}
	
	/**
	 * @return Doctrine\Common\CacheProvider
	 */
	public function _initDoctrineCache()
	{
		$cache = null;
		if (APPLICATION_ENV === 'development') {
			$cache = new DoctrineArrayCache();
		} else {
			$cache = new DoctrineApcCache();
		}
		return $cache;
	}
}
